import { useEffect, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { toast } from '@/components/ui/sonner';
import { api } from '@/lib/api';
import { ScaffoldHistoryRecord } from '@/types/scaffold';
import { PaginationResponse } from '@/types/common';
import { Loader2, RefreshCcw } from 'lucide-react';

const HistoryPage = () => {
  const [records, setRecords] = useState<ScaffoldHistoryRecord[]>([]);
  const [keyword, setKeyword] = useState('');
  const [loading, setLoading] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [total, setTotal] = useState(0);
  const pageSize = 20;

  const loadHistory = async (searchValue = keyword) => {
    try {
      setLoading(true);
      setErrorMessage(null);
      const data = await api.post<PaginationResponse<ScaffoldHistoryRecord>>('/generator/scaffold/logs/list', {
        keyword: searchValue,
        current: 1,
        pageSize,
      });
      setRecords(data?.records ?? []);
      setTotal(data?.total ?? 0);
    } catch (error) {
      console.error(error);
      const message = error instanceof Error ? error.message : '获取历史记录失败';
      toast.error(message);
      if (message.includes('403')) {
        setErrorMessage('您暂无权限查看生成历史，请联系管理员。');
      } else if (message.includes('404')) {
        setErrorMessage('历史记录接口未启用，可能是后端未开启数据库功能。');
      } else {
        setErrorMessage('获取生成历史失败，请稍后再试。');
      }
      setRecords([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadHistory();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className="space-y-6">
      {errorMessage ? (
        <Alert variant="destructive">
          <AlertTitle>无法加载生成历史</AlertTitle>
          <AlertDescription>{errorMessage}</AlertDescription>
        </Alert>
      ) : null}

      <Card>
        <CardHeader>
          <CardTitle>筛选条件</CardTitle>
        </CardHeader>
        <CardContent className="flex flex-col gap-3 md:flex-row md:items-center">
          <Input
            value={keyword}
            onChange={(event) => setKeyword(event.target.value)}
            placeholder="搜索模块名称、基础包或数据库类型"
            className="md:w-72"
          />
          <div className="flex gap-2">
            <Button onClick={() => loadHistory(keyword)} disabled={loading}>
              {loading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <RefreshCcw className="mr-2 h-4 w-4" />}
              查询
            </Button>
            <Button
              variant="outline"
              onClick={() => {
                setKeyword('');
                loadHistory('');
              }}
            >
              重置
            </Button>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>
            生成历史
            {total ? <span className="ml-2 text-sm text-muted-foreground">共 {total} 条</span> : null}
          </CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          {records.length === 0 ? (
            <div className="flex h-48 items-center justify-center text-sm text-muted-foreground">
              {loading ? '加载中...' : errorMessage ? '暂无法获取生成历史' : '暂无记录'}
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>模块名称</TableHead>
                  <TableHead>基础包</TableHead>
                  <TableHead>模块目录</TableHead>
                  <TableHead>数据库类型</TableHead>
                  <TableHead>区块链</TableHead>
                  <TableHead>生成方式</TableHead>
                  <TableHead>操作时间</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {records.map((record) => (
                  <TableRow key={record.id}>
                    <TableCell>{record.moduleName}</TableCell>
                    <TableCell className="text-xs text-muted-foreground">{record.basePackage}</TableCell>
                    <TableCell className="text-xs text-muted-foreground">{record.moduleBasePath ?? '-'}</TableCell>
                    <TableCell>
                      <Badge variant="outline">{record.databaseType ?? '未知'}</Badge>
                    </TableCell>
                    <TableCell>{record.enableBlockchain ? '是' : '否'}</TableCell>
                    <TableCell>{record.generateType}</TableCell>
                    <TableCell className="text-xs text-muted-foreground">
                      {new Date(record.createdAt).toLocaleString()}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
};

export default HistoryPage;

